import React from 'react';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import type { SitInfoItem } from '@/services/API.d';
import { columnsSitInfoItem } from '@/services/Column.d';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {
  addSit,
  notAvailableSit,
  querySitList,
  removeSit,
  availableSit,
  updateSit,
  usedSit,
} from '@/services/sitInfo';
import ProForm, { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';

type StateType = {
  createModalVisible: boolean;
  updateModalVisible: boolean;
  currentRow: SitInfoItem;
  selectedRowsState: SitInfoItem[];
};

class SitInfo extends React.Component<any, StateType> {
  private actionRef = React.createRef<any>();
  private formRef = React.createRef<any>();
  private temp: SitInfoItem = {
    stationId: 0,
    station: '',
    identifier: '',
    stationType: 1,
    state: 1,
  };
  public state = {
    createModalVisible: false,
    updateModalVisible: false,
    currentRow: this.temp,
    selectedRowsState: [],
  };

  handleModalVisible = (e: boolean) => {
    this.setState({
      createModalVisible: e,
    });
  };

  setCurrentRow = (currentRow: SitInfoItem) => {
    this.setState({
      currentRow,
    });
  };

  setSelectedRows = (selectedRowsState: SitInfoItem[]) => {
    this.setState({
      selectedRowsState,
    });
  };

  /**
   * 添加节点
   * @param fields
   */
  handleAdd = async (fields: SitInfoItem) => {
    const hide = message.loading('正在添加');

    try {
      const res = await addSit({ ...fields });
      hide();
      if (res.code === 200) {
        message.success(res.msg);
        return true;
      }
      message.error(res.msg);
      return false;
    } catch (error) {
      hide();
      message.error('添加失败，请重试！');
      return false;
    }
  };

  /**
   *  删除节点
   * @param selectedRows
   */
  handleRemove = async (selectedRows: SitInfoItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await removeSit(selectedRows.map((row) => row.stationId));
      hide();
      message.success('删除成功');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  /**
   *  状态更新节点
   * @param selectedRows
   * @param state
   */
  handleUpdateState = async (selectedRows: SitInfoItem[], state: number) => {
    const hide = message.loading('正在操作');
    if (!selectedRows) return true;
    try {
      if (state === 1) {
        await availableSit(selectedRows.map((row) => row.stationId));
      } else if (state === 2) {
        await usedSit(selectedRows.map((row) => row.stationId));
      } else if (state === 3) {
        await notAvailableSit(selectedRows.map((row) => row.stationId));
      }
      hide();
      message.success('操作成功');
      return true;
    } catch (error) {
      hide();
      message.error('操作失败，请重试');
      return false;
    }
  };

  /**
   * 更新节点
   * @param fields
   */
  handleUpdate = async (fields: SitInfoItem) => {
    const hide = message.loading('正在编辑');

    try {
      const res = await updateSit({ ...fields });
      hide();
      if (res.code === 200) {
        message.success(res.msg);
        return true;
      }
      message.error(res.msg);
      return true;
    } catch (error) {
      hide();
      message.error('编辑失败请重试！');
      return false;
    }
  };

  render() {
    const { selectedRowsState, createModalVisible, currentRow } = this.state;

    const { actionRef, formRef } = this;

    const columns: ProColumns<SitInfoItem>[] = columnsSitInfoItem;
    columns[columns.length - 1].render = (_, record) => (
      <>
        <Popconfirm
          title="删除此行？"
          onConfirm={async () => {
            await this.handleRemove([record]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="确定"
          cancelText="取消"
        >
          <a>删除</a>
        </Popconfirm>
      </>
    );
    return (
      <PageContainer>
        <ProTable<SitInfoItem>
          headerTitle="车位信息列表"
          actionRef={actionRef}
          rowKey={(record) => record.stationId}
          search={{
            labelWidth: 120,
          }}
          pagination={{
            showQuickJumper: true,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                this.setCurrentRow(this.temp);
                formRef.current?.setFieldsValue(this.temp);
                this.handleModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
          dateFormatter="string"
          request={ async (params) => {
            // 表单搜索项会从 params 传入，传递给后端接口。
            let res: any = {};
            await querySitList(params).then(v => {
              res = v;
              res.total = v.msg
            })
            return res;
          }}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => this.setSelectedRows(selectedRows),
          }}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
              </div>
            }
          >
            <Button
              onClick={async () => {
                await this.handleRemove(selectedRowsState);
                this.setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量删除
            </Button>
            <Button
              type="primary"
              onClick={async () => {
                await this.handleUpdateState(selectedRowsState, 1);
                this.setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量可用
            </Button>
            <Button
              onClick={async () => {
                await this.handleUpdateState(selectedRowsState, 2);
                this.setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量已使用
            </Button>
            <Button
              type="primary"
              onClick={async () => {
                await this.handleUpdateState(selectedRowsState, 3);
                this.setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量不可用
            </Button>
          </FooterToolbar>
        )}
        <ModalForm
          title="新建车位"
          formRef={formRef}
          visible={createModalVisible}
          onVisibleChange={this.handleModalVisible}
          onFinish={async (values) => {
            const success = await this.handleAdd(values as SitInfoItem);
            if (success) {
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
            return true;
          }}
        >
          <ProForm.Group>
            <ProFormText
              width="md"
              name="station"
              label="车位号"
              placeholder="请输入车位号"
              initialValue={currentRow.station}
              rules={[
                {
                  required: true,
                  message: '车位号为必填项',
                },
              ]}
            />
            <ProFormText
              width="md"
              name="identifier"
              label="车位标识"
              placeholder="请输入车位标识"
              initialValue={currentRow.identifier}
              rules={[
                {
                  required: true,
                  message: '车位标识为必填项',
                },
              ]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormSelect
              width="md"
              name="stationType"
              label="车位类型"
              placeholder="请选择车位类型"
              options={[
                {
                  value: 1,
                  label: '小型',
                },
                {
                  value: 2,
                  label: '中型',
                },
                {
                  value: 3,
                  label: '大型',
                },
              ]}
              initialValue={currentRow.stationType}
              rules={[
                {
                  required: true,
                  message: '车位类型为必填项',
                },
              ]}
            />
            <ProFormSelect
              options={[
                {
                  value: 1,
                  label: '可用',
                },
                {
                  value: 2,
                  label: '已使用',
                },
                {
                  value: 3,
                  label: '不可用',
                },
              ]}
              initialValue={currentRow.state}
              width="md"
              name="state"
              label="状态"
              placeholder="请选择状态"
              rules={[
                {
                  required: true,
                  message: '状态为必选项',
                },
              ]}
            />
          </ProForm.Group>
        </ModalForm>
      </PageContainer>
    );
  }
}

export default SitInfo;
